package com.wwj.my_ummary.goods.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wwj.my_ummary.goods.entity.Goods;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

/**
 * <p>
 * 商品表 Mapper 接口
 * </p>
 *
 * @author wwj
 * @since 2021-01-14
 */
public interface GoodsMapper extends BaseMapper<Goods> {
    /**
     * 查询商品库存
     *
     * @param id 商品id
     * @return 加 for update  变为悲观锁
     * 不加加 for update  变为乐观锁
     */
//    @Select("SELECT * FROM goods WHERE id = #{id} ")
    @Select("SELECT * FROM goods WHERE id = #{id} for update")
    Goods getStock(@Param("id") int id);

    /**
     * 扣减库存
     *
     * @param id      商品id
     * @param version 版本号
     * @return
     */
    @Update("UPDATE goods SET stock = stock - 1, version = version + 1 WHERE id = #{id} AND stock > 0 AND version = #{version}")
    int decreaseStockForVersion(@Param("id") int id, @Param("version") int version);

    int decreaseStockForVersions(@Param("id") int id, @Param("version") int version);
}
